
package com.hlkj.pay.app.merchant.impl;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.LocalContext;
import com.hlkj.framework.common.util.collection.CollectionUtils;
import com.hlkj.framework.common.util.id.IdUtils;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.IMerchantReportAppService;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelVirtualCommonConfig;
import com.hlkj.pay.common.CommonResultCode;
import com.hlkj.pay.common.MerchantResultCode;
import com.hlkj.pay.common.OpenApiResultCode;
import com.hlkj.pay.common.PayResultCode;
import com.hlkj.pay.config.ExtRocketMQTemplate;
import com.hlkj.pay.dto.LocalMerchantRequest;
import com.hlkj.pay.dto.merchant.VirtualBalanceDto;
import com.hlkj.pay.dto.merchant.report.*;
import com.hlkj.pay.enums.CommonEnum;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.gateway.merchant.IMerchantReportGateway;
import com.hlkj.pay.infrastructure.model.merchant.*;
import com.hlkj.pay.infrastructure.model.pay.PayChannelDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderInfoDO;
import com.hlkj.pay.service.common.IOperatedLogService;
import com.hlkj.pay.service.merchant.IMerchantApplicationService;
import com.hlkj.pay.service.merchant.IMerchantReportService;
import com.hlkj.pay.service.merchant.IMerchantService;
import com.hlkj.pay.service.pay.IPayChannelService;
import com.hlkj.pay.service.pay.IProviderService;
import com.hlkj.pay.util.OrderCodeUtil;
import com.hlkj.pay.vo.merchant.req.access.MerchantReportCertReq;
import com.hlkj.pay.vo.merchant.req.report.*;
import com.hlkj.pay.vo.merchant.resp.common.MerchantLicenseResp;
import com.hlkj.pay.vo.merchant.resp.report.*;
import com.hlkj.pay.vo.openapi.merchant.req.report.OpenApiMerchantReportQueryReq;
import com.hlkj.pay.vo.openapi.merchant.req.report.OpenApiMerchantReportReq;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.BeanUtil;

/**
 * @author HlpayTeam
 * @date 2024/12/20 13:19
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Validated
public class MerchantReportAppServiceImpl implements IMerchantReportAppService {

    private final IMerchantReportService merchantReportService;

    private final IOperatedLogService operatedLogService;

    private final IMerchantService merchantService;

    private final IProviderService providerService;

    private final IPayChannelService payChannelService;

    private final ExtRocketMQTemplate extRocketMQTemplate;

    private final IMerchantReportGateway merchantReportGateway;

    private final MerchantReportStatusProcessHandler merchantReportStatusProcessHandler;

    private final IMerchantApplicationService merchantApplicationService;


    private final MerchantReportChannelService merchantReportChannelService;

    private final OrderCodeUtil orderCodeUtil;

    @Override
    public CommonResult<Long> saveReport(MerchantReportReq merchantReportReq) {
        log.info("saveAccess merchantReportReq:{}", JsonUtils.toJsonString(merchantReportReq));
        try {
            CommonResult<MerchantReportDto> commonResult = processAccess(merchantReportReq, MerchantEnum.ACCESS_STATUS.DRAFT);
            if (!commonResult.isSuccess()) {
                return CommonResult.error(commonResult.getCode(), commonResult.getMsg());
            }
            return CommonResult.success(commonResult.getData().getMerchantReportInfo().getId());
        }
        catch (Exception e) {
            log.error("saveAccess error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<MerchantReportDto> submitReport(MerchantReportReq merchantReportReq) {
        log.info("submitReport merchantReportReq:{}", JsonUtils.toJsonString(merchantReportReq));
        try {
            CommonResult<MerchantReportDto> commonResult = processAccess(merchantReportReq, MerchantEnum.ACCESS_STATUS.SUBMIT);
            if (!commonResult.isSuccess()) {
                return CommonResult.error(commonResult.getCode(), commonResult.getMsg());
            }
            // 发送审核 mq
            MerchantReportInfoDO merchantReportInfo = commonResult.getData().getMerchantReportInfo();
            Long id = merchantReportInfo.getId();
            return commonResult;
        }
        catch (Exception e) {
            log.error("submitAccess error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<MerchantReportDto> submitReport(OpenApiMerchantReportReq merchantReportReq) {
        log.info("submitReport merchantReportReq:{}", JsonUtils.toJsonString(merchantReportReq));
        try {
            CommonResult<MerchantReportDto> commonResult = processAccess(merchantReportReq, MerchantEnum.ACCESS_STATUS.SUBMIT);
            if (!commonResult.isSuccess()) {
                return CommonResult.error(commonResult.getCode(), commonResult.getMsg());
            }
            // 发送审核 mq
            MerchantReportInfoDO merchantReportInfo = commonResult.getData().getMerchantReportInfo();
            Long id = merchantReportInfo.getId();
            return commonResult;
        }
        catch (Exception e) {
            log.error("submitAccess error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<MerchantReportDto> reportDetail(OpenApiMerchantReportQueryReq accessQueryReq) {
        log.info("reportDetail accessQueryReq:{}", JsonUtils.toJsonString(accessQueryReq));
        try {
            if (!StringUtils.hasText(accessQueryReq.getMchRequestId()) && !StringUtils.hasText(accessQueryReq.getRequestId())) {
                return CommonResult.error(CommonResultCode.PARAMETER_MISSING);
            }
            MerchantReportInfoDO merchantAccessInfoDO = null;
            if (StringUtils.hasText(accessQueryReq.getMchRequestId())) {
                merchantAccessInfoDO = merchantReportService.queryByMchRequestId(LocalContext.get().getSn(), accessQueryReq.getMchRequestId());
                if (merchantAccessInfoDO == null) {
                    return CommonResult.error(OpenApiResultCode.DATA_NOT_EXIST);
                }
            }
            else if (StringUtils.hasText(accessQueryReq.getRequestId())) {
                merchantAccessInfoDO = merchantReportService.queryByRequestId(accessQueryReq.getRequestId());
                if (merchantAccessInfoDO == null) {
                    return CommonResult.error(OpenApiResultCode.DATA_NOT_EXIST);
                }
            }
            MerchantReportDto merchantReportDto = merchantReportService.domainDetail(merchantAccessInfoDO.getId());
            return CommonResult.success(merchantReportDto);
        }
        catch (Exception e) {
            log.error("submitAccess error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<String> getSignUrl(Long id) {
        try {
            MerchantReportInfoDO merchantReportInfoDO = merchantReportService.detail(id);
            if(merchantReportInfoDO == null){
                return CommonResult.error(OpenApiResultCode.DATA_NOT_EXIST);
            }
            String signUrl = null;
            // 判断是否待签约状态
            if(merchantReportInfoDO.getStatus() == MerchantEnum.REPORT_STATUS.WAIT_SIGN.getCode() || merchantReportInfoDO.getStatus() == MerchantEnum.REPORT_STATUS.WAIT_SIGNING.getCode()){
                CommonResult<String> commonResult = merchantReportGateway.getSignUrl(merchantReportInfoDO);
                if (!commonResult.isSuccess()) {
                    return CommonResult.error(commonResult.getCode(), commonResult.getMsg());
                }
                signUrl = commonResult.getData();
                // 更新签约链接
                if(StrUtil.isNotEmpty(signUrl)){
                    MerchantReportInfoDO updateInfo = new MerchantReportInfoDO();
                    updateInfo.setId(id);
                    updateInfo.setSignLink(signUrl);
                    merchantReportService.updateReportInfo(updateInfo);
                }
            }
            return CommonResult.success(signUrl);

        }
        catch (Exception e) {
            log.error("getSignUrl error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<MerchantReportResp> merchantReportInfo(Long id) {
        MerchantReportDto merchantReportDto = merchantReportService.domainDetail(id);
        if (merchantReportDto == null) {
            return CommonResult.success(null);
        }
        // 主表
        MerchantReportInfoDO merchantReportInfoDO = merchantReportDto.getMerchantReportInfo();
        MerchantReportResp merchantReport = BeanUtil.copy(merchantReportInfoDO, MerchantReportResp.class);
        MerchantReportInfoResp merchantReportInfo = BeanUtil.copy(merchantReportInfoDO, MerchantReportInfoResp.class);

        merchantReport.setProviderName(providerService.queryByCode(merchantReport.getProviderCode()).getName());
        merchantReport.setChannelName(payChannelService.queryByCode(merchantReport.getChannelCode()).getName());
        merchantReport.setMerchantReportInfo(merchantReportInfo);

        // 进件营业执照信息
        MerchantLicenseDO merchantReportLicenseDO = merchantReportDto.getMerchantReportLicense();
        // 进件法人信息
        MerchantCertInfoDO merchantReportLegalDO = merchantReportDto.getMerchantReportLegal();
        // 联系人信息
        MerchantCertInfoDO merchantReportContactDO = merchantReportDto.getMerchantReportContact();
        // 实际控制人
        MerchantCertInfoDO merchantReportControllerDO = merchantReportDto.getMerchantReportController();
        // 进件受益人信息
        List<MerchantCertInfoDO> merchantReportBenefits = merchantReportDto.getMerchantReportBenefitList();
        // 企业控股股东信息
        List<MerchantCertInfoDO> merchantReportShareholdersList = merchantReportDto.getMerchantReportShareholderList();
        // 经营信息
        MerchantReportBusinessDO merchantReportBusinessDO = merchantReportDto.getMerchantReportBusiness();
        // 进件结算卡信息
        MerchantCardDO merchantReportCardDO = merchantReportDto.getMerchantReportCard();
        if (merchantReportLegalDO != null) {
            MerchantReportCertResp merchantReportLegal = BeanUtil.copy(merchantReportLegalDO, MerchantReportCertResp.class);
            merchantReportLegal.setEmail(merchantReportLegalDO.getOtherValue());
            merchantReportInfo.setMerchantReportLegal(merchantReportLegal);
        }
        if (merchantReportControllerDO != null) {
            MerchantReportCertResp merchantReportController = BeanUtil.copy(merchantReportControllerDO, MerchantReportCertResp.class);
            merchantReportInfo.setMerchantReportController(merchantReportController);
        }
        if (merchantReportContactDO != null) {
            MerchantReportCertResp merchantReportContact = BeanUtil.copy(merchantReportContactDO, MerchantReportCertResp.class);
            merchantReportContact.setEmail(merchantReportContactDO.getOtherValue());
            merchantReportInfo.setMerchantReportContact(merchantReportContact);
        }
        if (merchantReportLicenseDO != null) {
            MerchantLicenseResp merchantReportLicense = BeanUtil.copy(merchantReportLicenseDO, MerchantLicenseResp.class);
            if(StrUtil.isNotEmpty(merchantReportLicenseDO.getRegisteredCapital())){
                merchantReportLicense.setRegisteredCapital(new BigDecimal(merchantReportLicenseDO.getRegisteredCapital()));
            }
            merchantReportInfo.setMerchantReportLicense(merchantReportLicense);
        }
        if (!CollectionUtils.isEmpty(merchantReportBenefits)) {
            List<MerchantReportCertResp> benefitResps = new ArrayList<>();
            merchantReportBenefits.stream().forEach(merchantReportCertInfoDO -> {
                MerchantReportCertResp benefitResp = BeanUtil.copy(merchantReportCertInfoDO, MerchantReportCertResp.class);
                benefitResps.add(benefitResp);
            });
            merchantReportInfo.setMerchantReportBenefitList(benefitResps);
        }
        if (!CollectionUtils.isEmpty(merchantReportShareholdersList)) {
            List<MerchantReportCertResp> merchantReportShareholders = BeanUtil.copy(merchantReportShareholdersList, MerchantReportCertResp.class);
            merchantReportInfo.setMerchantReportShareholderList(merchantReportShareholders);
        }
        if (merchantReportBusinessDO != null) {
            MerchantReportBusinessResp accessBusiness = BeanUtil.copy(merchantReportBusinessDO, MerchantReportBusinessResp.class);
            // 经营信息
            MerchantReportBusinessOtherDataDto businessOtherDataDto = JsonUtils.parseObject(merchantReportBusinessDO.getOtherDataJson(), MerchantReportBusinessOtherDataDto.class);
            if(businessOtherDataDto!=null){
                accessBusiness.setOpenBank(businessOtherDataDto.getOpenBank());
                accessBusiness.setBusinessDesc(businessOtherDataDto.getBusinessDesc());
                accessBusiness.setOrderUrl(businessOtherDataDto.getOrderUrl());
                accessBusiness.setGvmUrl(businessOtherDataDto.getGvmUrl());
                accessBusiness.setShopHomeUrl(businessOtherDataDto.getShopHomeUrl());
            }
            merchantReport.setMerchantReportBusiness(accessBusiness);

        }
        if (merchantReportCardDO != null) {
            MerchantReportCardResp merchantReportCardResp = BeanUtil.copy(merchantReportCardDO, MerchantReportCardResp.class);
            merchantReport.setMerchantReportCard(merchantReportCardResp);
        }
        // if
        // (MerchantEnum.REPORT_STATUS.CHANNEL_APPROVE.getCode().equals(merchantReportInfoDO.getStatus()))
        // {
        merchantReportStatusProcessHandler.processReportMessage(id);
        // }
        return CommonResult.success(merchantReport);
    }

    @Override
    public CommonResult<Void> platApprove(MerchantReportApproveReq merchantReportApproveReq) {
        log.info("platApprove merchantReportApproveReq:{}", JsonUtils.toJsonString(merchantReportApproveReq));
        try {
            Set<Long> ids = merchantReportApproveReq.getIds();
            CommonEnum.YES_NO_TYPE yesNoType = CommonEnum.YES_NO_TYPE.from(merchantReportApproveReq.getStatus());
            for (Long id : ids) {
                MerchantReportInfoDO merchantReportInfoDO = merchantReportService.detail(id);
                MerchantReportInfoDO updateMerchantReportInfo=new MerchantReportInfoDO();
                updateMerchantReportInfo.setId(merchantReportInfoDO.getId());
                if (merchantReportInfoDO == null) {
                    log.warn("merchantReportApproveReq 数据不存在 id:{}", id);
                    return CommonResult.error(MerchantResultCode.MERCHANT_ACCESS_NOT_EXIST);
                }
                switch (yesNoType) {
                    case YES:
                        if (merchantReportInfoDO.getStatus().equals(MerchantEnum.REPORT_STATUS.CHANNEL_APPROVE.getCode())) {
                            return CommonResult.success();
                        }
                }
                MerchantEnum.REPORT_STATUS channelApprove;
                switch (yesNoType) {
                    case NO:
                        channelApprove = MerchantEnum.REPORT_STATUS.APPROVE_REFUSE;
                        break;
                    default:
                        // if (merchantReportInfoDO.getLastStatus() == null ||
                        // merchantReportInfoDO.getLastStatus() <=
                        // MerchantEnum.REPORT_STATUS.CHANNEL_APPROVE.getCode()) {
                        // channelApprove = MerchantEnum.REPORT_STATUS.CHANNEL_WAIT_APPROVE;
                        // }
                        // else {
                        // channelApprove =
                        // MerchantEnum.REPORT_STATUS.from(merchantReportInfoDO.getLastStatus());
                        // }
                        channelApprove = MerchantEnum.REPORT_STATUS.CHANNEL_WAIT_APPROVE;
                }
                if (merchantReportApproveReq.getRemark() == null) {
                    merchantReportApproveReq.setRemark("");
                }
                if (yesNoType == CommonEnum.YES_NO_TYPE.NO) {
                    operatedLogService.save(id, MerchantEnum.MERCHANT_LOG_TYPE.REPORT, "机构审核驳回", merchantReportApproveReq.getRemark());
                } else {
                    operatedLogService.save(id, MerchantEnum.MERCHANT_LOG_TYPE.REPORT, "机构审核成功", "报备审核通过");
                }
                merchantReportService.updateStatus(id, channelApprove, merchantReportApproveReq.getRemark());
                updateMerchantReportInfo.setStatus(channelApprove.getCode());
                updateMerchantReportInfo.setMessage(merchantReportApproveReq.getRemark());
                updateMerchantReportInfo.setBankStatus(MerchantEnum.REPORT_BANK_STATUS.INIT.getCode());
                updateMerchantReportInfo.setSignLink("");
                // updateMerchantReportInfo.setLastStatus();
                // merchantReportService.updateStatus(id, channelApprove, merchantReportApproveReq.getRemark());
                merchantReportService.updateReportInfo(updateMerchantReportInfo);
                // 发送审核通过message
                merchantReportStatusProcessHandler.processReportMessage(id);
            }
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("platApprove error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> delete(Long id) {
        log.info("delete id:{}", id);
        try {
            if (id == null) {
                return CommonResult.error(CommonResultCode.PARAMETER_MISSING);
            }
            MerchantReportInfoDO merchantReportInfoDO = merchantReportService.detail(id);
            if (merchantReportInfoDO == null) {
                log.warn("delete 数据不存在 id:{}", id);
                return CommonResult.error(MerchantResultCode.MERCHANT_ACCESS_NOT_EXIST);
            }
            merchantReportService.delete(id);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("delete error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public void processAccessMessage(MerchantReportConsumerDto merchantReportConsumerDto) {
        log.info("processAccessMessage merchantReportConsumerDto:{}", JsonUtils.toJsonString(merchantReportConsumerDto));
        try {
            merchantReportStatusProcessHandler.processReportMessage(merchantReportConsumerDto);
        }
        catch (Exception e) {
            log.error("processAccessMessage error:{}", e.getMessage(), e);
        }
    }

    @Override
    public CommonResult<Void> merchantReportSmsSend(MerchantReportSmsSendDto merchantReportSmsSendDto) {
        log.info("merchantReportSms merchantReportSmsSendDto:{}", JsonUtils.toJsonString(merchantReportSmsSendDto));
        try {
            MerchantReportInfoDO merchantReportInfoDO = merchantReportService.detail(merchantReportSmsSendDto.getId());
            if (merchantReportInfoDO.getStatus() < MerchantEnum.REPORT_STATUS.CHANNEL_APPROVE.getCode()
                    || MerchantEnum.REPORT_STATUS.APPROVE_REFUSE.getCode().equals(merchantReportInfoDO.getStatus())) {
                return CommonResult.error(MerchantResultCode.MERCHANT_ACCESS_NOT_EXIST);
            }
            return merchantReportGateway.merchantReportSmsSend(merchantReportInfoDO, merchantReportSmsSendDto);
        }
        catch (Exception e) {
            log.error("processAccessMessage error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> merchantReportSmsCode(MerchantReportSmsCodeDto merchantReportSmsCodeDto) {
        log.info("merchantReportSms merchantReportSmsCodeDto:{}", JsonUtils.toJsonString(merchantReportSmsCodeDto));
        try {
            MerchantReportInfoDO merchantReportInfoDO = merchantReportService.detail(merchantReportSmsCodeDto.getId());
            if (merchantReportInfoDO.getStatus() < MerchantEnum.REPORT_STATUS.CHANNEL_APPROVE.getCode()
                    || MerchantEnum.REPORT_STATUS.APPROVE_REFUSE.getCode().equals(merchantReportInfoDO.getStatus())) {
                return CommonResult.error(MerchantResultCode.MERCHANT_ACCESS_NOT_EXIST);
            }
            return merchantReportGateway.merchantReportSmsCode(merchantReportInfoDO, merchantReportSmsCodeDto);
        }
        catch (Exception e) {
            log.error("processAccessMessage error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<MerchantReportBalanceDto> merchantReportBalance(Long id) {
        try {
            MerchantAppChannelDO merchantAppChannelDO = merchantApplicationService.queryDetailByAccessId(id, MerchantEnum.DATA_RELATION_TYPE.REPORT);
            if (merchantAppChannelDO == null) {
                return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EXIST);
            }
            // if (!CommonEnum.YES_NO_TYPE.YES.getCode().equals(merchantAppChannelDO.getStatus())) {
            //     return CommonResult.error(MerchantResultCode.MERCHANT_APP_NOT_EFFECT);
            // }
            CommonResult<VirtualBalanceDto> commonResult = merchantReportGateway.balanceQuery(merchantAppChannelDO.getCode());
            MerchantReportBalanceDto merchantReportBalanceDto = new MerchantReportBalanceDto();
            if (!commonResult.isSuccess()) {
                return CommonResult.error(commonResult.getCode(), commonResult.getMsg());
            }
            VirtualBalanceDto data = commonResult.getData();
            merchantReportBalanceDto.setChannelBalance(data.getBalance());
            return CommonResult.success(merchantReportBalanceDto);

        }
        catch (Exception e) {
            log.error("processAccessMessage error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    @Override
    public CommonResult<Void> merchantReportAllot(Long id) {
        try {
            MerchantReportDto merchantReportDto = merchantReportService.domainDetail(id);
            if (merchantReportDto == null) {
                return CommonResult.error(CommonResultCode.DATA_NOT_EXIST);
            }
            merchantReportChannelService.allot(merchantReportDto);
            return CommonResult.success();
        }
        catch (Exception e) {
            log.error("processAccessMessage error:{}", e.getMessage(), e);
            return CommonResult.error(CommonResultCode.SERVICE_ERROR);
        }
    }

    /**
     * 进件保存处理
     *
     * @param merchantReportReq
     * @param accessStatus
     * @return
     */
    CommonResult<MerchantReportDto> processAccess(MerchantReportReq merchantReportReq, MerchantEnum.ACCESS_STATUS accessStatus) {
        MerchantReportInfoReq merchantReportInfo = merchantReportReq.getMerchantReportInfo();
        // 联系人同法人
        if (CommonEnum.YES_NO_TYPE.YES.getCode().equals(merchantReportInfo.getContactType())) {
            merchantReportInfo.setMerchantReportContact(merchantReportInfo.getMerchantReportLegal());
        }
        // 控制人同法人
        if (CommonEnum.YES_NO_TYPE.YES.getCode().equals(merchantReportInfo.getControllerType())) {
            merchantReportInfo.setMerchantReportController(merchantReportInfo.getMerchantReportLegal());
        }
        if(!StringUtils.hasText(merchantReportReq.getSn())){
            merchantReportReq.setSn(LocalContext.get().getQuerySn());
        }
        MerchantInfoDO merchantInfoDO = merchantService.queryMerchant(merchantReportReq.getSn());
        if (merchantInfoDO == null) {
            return CommonResult.error(MerchantResultCode.MERCHANT_NOT_EXIST);
        }
        ProviderInfoDO providerInfoDO = providerService.queryByCode(merchantReportReq.getProviderCode());
        if (providerInfoDO == null) {
            return CommonResult.error(PayResultCode.PROVIDER_NOT_EXITS);
        }
        PayChannelDO payChannelDO = payChannelService.queryByCode(merchantReportReq.getChannelCode());
        if (payChannelDO == null) {
            return CommonResult.error(PayResultCode.PAY_CHANNEL_NOT_EXITS);
        }
        MerchantReportDto merchantReportDto = new MerchantReportDto();

        MerchantReportBusinessReq merchantReportBusiness = merchantReportReq.getMerchantReportBusiness();
        // 进件主表信息
        MerchantReportInfoDO merchantReportInfoDO = new MerchantReportInfoDO();
        merchantReportInfoDO.setSn(merchantReportReq.getSn());
        merchantReportInfoDO.setProviderCode(merchantReportReq.getProviderCode());
        merchantReportInfoDO.setChannelCode(merchantReportReq.getChannelCode());
        merchantReportInfoDO.setSn(merchantReportReq.getSn());
        merchantReportInfoDO.setId(merchantReportReq.getId());
        merchantReportInfoDO.setControllerType(merchantReportInfo.getControllerType());
        merchantReportInfoDO.setContactType(merchantReportInfo.getContactType());
        merchantReportInfoDO.setType(merchantReportInfo.getType());
        merchantReportInfoDO.setMessage("");
        merchantReportDto.setMerchantReportInfo(merchantReportInfoDO);
        // 进件营业执照信息
        MerchantReportLicenseReq merchantReportLicense = merchantReportInfo.getMerchantReportLicense();
        // 进件法人信息
        MerchantCertInfoDO merchantReportLegalDO = BeanUtil.copy(merchantReportInfo.getMerchantReportLegal(), MerchantCertInfoDO.class);
        merchantReportLegalDO.setOtherValue(merchantReportInfo.getMerchantReportLegal().getEmail());
        if (merchantReportLicense != null) {
            MerchantLicenseDO merchantReportLicenseDO = BeanUtil.copy(merchantReportLicense, MerchantLicenseDO.class);
            merchantReportDto.setMerchantReportLicense(merchantReportLicenseDO);
            merchantReportInfoDO.setName(merchantReportLicenseDO.getName());
        }
        else {
            merchantReportInfoDO.setName(merchantReportLegalDO.getName());
        }
        merchantReportDto.setMerchantReportLegal(merchantReportLegalDO);

        // 联系人信息
        MerchantCertInfoDO merchantReportContactDO = BeanUtil.copy(merchantReportInfo.getMerchantReportContact(), MerchantCertInfoDO.class);
        merchantReportContactDO.setOtherValue(merchantReportInfo.getMerchantReportContact().getEmail());
        merchantReportDto.setMerchantReportContact(merchantReportContactDO);

        // 实际控制人
        MerchantReportCertReq merchantReportController = merchantReportInfo.getMerchantReportController();
        if (merchantReportController != null) {
            MerchantCertInfoDO merchantReportControllerDO = BeanUtil.copy(merchantReportInfo.getMerchantReportController(), MerchantCertInfoDO.class);
            merchantReportDto.setMerchantReportController(merchantReportControllerDO);
        }
        // 进件受益人信息
        List<MerchantReportCertReq> merchantReportBenefitList = merchantReportInfo.getMerchantReportBenefitList();
        if (!CollectionUtils.isEmpty(merchantReportBenefitList)) {
            List<MerchantCertInfoDO> merchantReportBenefits = new ArrayList<>();
            merchantReportBenefitList.stream().forEach(merchantReportBenefitReq -> {
                MerchantCertInfoDO merchantReportCertInfoDO = BeanUtil.copy(merchantReportBenefitReq, MerchantCertInfoDO.class);
                merchantReportBenefits.add(merchantReportCertInfoDO);
            });
            merchantReportDto.setMerchantReportBenefitList(merchantReportBenefits);
        }
        // 企业控股股东信息
        List<MerchantReportCertReq> merchantReportShareholderList = merchantReportInfo.getMerchantReportShareholderList();
        if (!CollectionUtils.isEmpty(merchantReportBenefitList)) {
            List<MerchantCertInfoDO> merchantReportShareholders = BeanUtil.copy(merchantReportShareholderList, MerchantCertInfoDO.class);
            merchantReportDto.setMerchantReportShareholderList(merchantReportShareholders);
        }
        // 经营信息
        // 经营信息
        MerchantReportBusinessDO merchantReportBusinessDO = BeanUtil.copy(merchantReportBusiness, MerchantReportBusinessDO.class);
        MerchantReportBusinessOtherDataDto businessOtherDataDto = BeanUtil.copy(merchantReportBusiness, MerchantReportBusinessOtherDataDto.class);
        merchantReportBusinessDO.setOtherDataJson(JsonUtils.toJsonString(businessOtherDataDto));
        // 进件结算卡信息
        MerchantCardDO merchantReportCardDO = BeanUtil.copy(merchantReportReq.getMerchantReportCard(), MerchantCardDO.class);
        merchantReportDto.setMerchantReportBusiness(merchantReportBusinessDO);
        merchantReportDto.setMerchantReportCard(merchantReportCardDO);
        merchantReportInfoDO.setSnType(merchantInfoDO.getSnType());
        merchantReportInfoDO.setSysType(LocalContext.get().getSysType());
        merchantReportInfoDO.setStatus(accessStatus.getCode());
        merchantReportInfoDO.setMessage("");

        if (merchantReportReq.getId() == null) {
            merchantReportInfoDO = merchantReportDto.getMerchantReportInfo();
            merchantReportInfoDO.setRequestId(IdUtils.getSnowflakeNextIdStr());
            merchantReportInfoDO.setUserId(orderCodeUtil.orderNo("HDT", 3));
            ProviderChannelConfigDO providerChannelConfigDO = providerService.queryConfig(merchantReportInfoDO.getProviderCode(), merchantReportInfoDO.getChannelCode());
            ChannelVirtualCommonConfig channelVirtualCommonConfig = JsonUtils.parseObject(providerChannelConfigDO.getParamsConfig(), ChannelVirtualCommonConfig.class);
            merchantReportInfoDO.setBankName(channelVirtualCommonConfig.getBankName());
            merchantReportService.saveReport(merchantReportDto);
            operatedLogService.save(merchantReportDto.getMerchantReportInfo().getId(), MerchantEnum.MERCHANT_LOG_TYPE.REPORT, "新增报备", "新增报备信息");
        }
        else {
            // 恢复到上一个状态
            MerchantReportInfoDO detail = merchantReportService.detail(merchantReportReq.getId());
            if (!StringUtils.hasText(detail.getUserId())) {
                merchantReportInfoDO.setUserId(orderCodeUtil.orderNo("HDT", 3));
            }
            Integer lastStatus = detail.getLastStatus();
            if(lastStatus != null && lastStatus > 10){
                lastStatus = lastStatus/10;
            }
            if (lastStatus != null && lastStatus > MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE.getCode()) {
                merchantReportInfoDO.setStatus(detail.getLastStatus());
            }
            merchantReportService.updateReport(merchantReportDto);
            operatedLogService.save(merchantReportDto.getMerchantReportInfo().getId(), MerchantEnum.MERCHANT_LOG_TYPE.REPORT, "修改报备信息", "修改报备信息");
        }
        return CommonResult.success(merchantReportDto);
    }
    /**
     * 进件保存处理
     *
     * @param openApiMerchantReportReq
     * @param accessStatus
     * @return
     */
    CommonResult<MerchantReportDto> processAccess(OpenApiMerchantReportReq openApiMerchantReportReq, MerchantEnum.ACCESS_STATUS accessStatus) {
        MerchantReportInfoReq merchantReportInfo = openApiMerchantReportReq.getMerchantReportInfo();
        // 联系人同法人
        if (CommonEnum.YES_NO_TYPE.YES.getCode().equals(merchantReportInfo.getContactType())) {
            merchantReportInfo.setMerchantReportContact(merchantReportInfo.getMerchantReportLegal());
        }
        // 控制人同法人
        if (CommonEnum.YES_NO_TYPE.YES.getCode().equals(merchantReportInfo.getControllerType())) {
            merchantReportInfo.setMerchantReportController(merchantReportInfo.getMerchantReportLegal());
        }

        ProviderInfoDO providerInfoDO = providerService.queryByCode(openApiMerchantReportReq.getProviderCode());
        if (providerInfoDO == null) {
            return CommonResult.error(PayResultCode.PROVIDER_NOT_EXITS);
        }
        PayChannelDO payChannelDO = payChannelService.queryByCode(openApiMerchantReportReq.getChannelCode());
        if (payChannelDO == null) {
            return CommonResult.error(PayResultCode.PAY_CHANNEL_NOT_EXITS);
        }
        MerchantReportDto merchantReportDto = new MerchantReportDto();

        MerchantReportBusinessReq merchantReportBusiness = openApiMerchantReportReq.getMerchantReportBusiness();
        // 进件主表信息
        MerchantReportInfoDO merchantReportInfoDO = new MerchantReportInfoDO();
        merchantReportInfoDO.setProviderCode(openApiMerchantReportReq.getProviderCode());
        merchantReportInfoDO.setChannelCode(openApiMerchantReportReq.getChannelCode());
        LocalMerchantRequest localRequest=(LocalMerchantRequest)LocalContext.get();
        merchantReportInfoDO.setSn(localRequest.getSn());
        if(StringUtils.hasText(openApiMerchantReportReq.getMchRequestId())){
            MerchantReportInfoDO reportInfoDO = merchantReportService.queryByMchRequestId(localRequest.getSn(), openApiMerchantReportReq.getMchRequestId());
            if(reportInfoDO==null){
                return CommonResult.error(OpenApiResultCode.DATA_NOT_EXIST);
            }
            merchantReportInfoDO.setId(reportInfoDO.getId());
        }


        merchantReportInfoDO.setControllerType(merchantReportInfo.getControllerType());
        merchantReportInfoDO.setContactType(merchantReportInfo.getContactType());
        merchantReportInfoDO.setType(merchantReportInfo.getType());
        merchantReportInfoDO.setMessage("");
        merchantReportDto.setMerchantReportInfo(merchantReportInfoDO);
        // 进件营业执照信息
        MerchantReportLicenseReq merchantReportLicense = merchantReportInfo.getMerchantReportLicense();
        // 进件法人信息
        MerchantCertInfoDO merchantReportLegalDO = BeanUtil.copy(merchantReportInfo.getMerchantReportLegal(), MerchantCertInfoDO.class);
        merchantReportLegalDO.setOtherValue(merchantReportInfo.getMerchantReportLegal().getEmail());
        if (merchantReportLicense != null) {
            MerchantLicenseDO merchantReportLicenseDO = BeanUtil.copy(merchantReportLicense, MerchantLicenseDO.class);
            merchantReportDto.setMerchantReportLicense(merchantReportLicenseDO);
            merchantReportInfoDO.setName(merchantReportLicenseDO.getName());
        }
        else {
            merchantReportInfoDO.setName(merchantReportLegalDO.getName());
        }
        merchantReportDto.setMerchantReportLegal(merchantReportLegalDO);

        // 联系人信息
        MerchantCertInfoDO merchantReportContactDO = BeanUtil.copy(merchantReportInfo.getMerchantReportContact(), MerchantCertInfoDO.class);
        merchantReportContactDO.setOtherValue(merchantReportInfo.getMerchantReportContact().getEmail());
        merchantReportDto.setMerchantReportContact(merchantReportContactDO);

        // 实际控制人
        MerchantReportCertReq merchantReportController = merchantReportInfo.getMerchantReportController();
        if (merchantReportController != null) {
            MerchantCertInfoDO merchantReportControllerDO = BeanUtil.copy(merchantReportInfo.getMerchantReportController(), MerchantCertInfoDO.class);
            merchantReportDto.setMerchantReportController(merchantReportControllerDO);
        }
        // 进件受益人信息
        List<MerchantReportCertReq> merchantReportBenefitList = merchantReportInfo.getMerchantReportBenefitList();
        if (!CollectionUtils.isEmpty(merchantReportBenefitList)) {
            List<MerchantCertInfoDO> merchantReportBenefits = new ArrayList<>();
            merchantReportBenefitList.stream().forEach(merchantReportBenefitReq -> {
                MerchantCertInfoDO merchantReportCertInfoDO = BeanUtil.copy(merchantReportBenefitReq, MerchantCertInfoDO.class);
                merchantReportBenefits.add(merchantReportCertInfoDO);
            });
            merchantReportDto.setMerchantReportBenefitList(merchantReportBenefits);
        }
        // 企业控股股东信息
        List<MerchantReportCertReq> merchantReportShareholderList = merchantReportInfo.getMerchantReportShareholderList();
        if (!CollectionUtils.isEmpty(merchantReportBenefitList)) {
            List<MerchantCertInfoDO> merchantReportShareholders = BeanUtil.copy(merchantReportShareholderList, MerchantCertInfoDO.class);
            merchantReportDto.setMerchantReportShareholderList(merchantReportShareholders);
        }
        // 经营信息
        MerchantReportBusinessDO merchantReportBusinessDO = BeanUtil.copy(merchantReportBusiness, MerchantReportBusinessDO.class);
        MerchantReportBusinessOtherDataDto businessOtherDataDto = BeanUtil.copy(merchantReportBusiness, MerchantReportBusinessOtherDataDto.class);
        merchantReportBusinessDO.setOtherDataJson(JsonUtils.toJsonString(businessOtherDataDto));

        // 进件结算卡信息
        MerchantCardDO merchantReportCardDO = BeanUtil.copy(openApiMerchantReportReq.getMerchantReportCard(), MerchantCardDO.class);
        merchantReportDto.setMerchantReportBusiness(merchantReportBusinessDO);
        merchantReportDto.setMerchantReportCard(merchantReportCardDO);
        merchantReportInfoDO.setSnType(localRequest.getMerchantInfoDO().getSnType());
        merchantReportInfoDO.setSysType(LocalContext.get().getSysType());
        merchantReportInfoDO.setStatus(accessStatus.getCode());
        merchantReportInfoDO.setMessage("");

        if (merchantReportInfoDO.getId() == null) {
            merchantReportInfoDO = merchantReportDto.getMerchantReportInfo();
            merchantReportInfoDO.setRequestId(IdUtils.getSnowflakeNextIdStr());
            merchantReportInfoDO.setUserId(orderCodeUtil.orderNo("HDT", 3));
            ProviderChannelConfigDO providerChannelConfigDO = providerService.queryConfig(merchantReportInfoDO.getProviderCode(), merchantReportInfoDO.getChannelCode());
            ChannelVirtualCommonConfig channelVirtualCommonConfig = JsonUtils.parseObject(providerChannelConfigDO.getParamsConfig(), ChannelVirtualCommonConfig.class);
            merchantReportInfoDO.setBankName(channelVirtualCommonConfig.getBankName());
            merchantReportService.saveReport(merchantReportDto);
            operatedLogService.save(merchantReportDto.getMerchantReportInfo().getId(), MerchantEnum.MERCHANT_LOG_TYPE.REPORT, "新增报备", "新增报备信息");
        }
        else {
            // 恢复到上一个状态
            MerchantReportInfoDO detail = merchantReportService.detail(merchantReportInfoDO.getId());
            // if (!StringUtils.hasText(detail.getUserId())) {
            //     merchantReportInfoDO.setUserId(orderCodeUtil.orderNo("HDT", 3));
            // }
            if (detail.getLastStatus() != null && detail.getLastStatus() > MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE.getCode()) {
                merchantReportInfoDO.setStatus(detail.getLastStatus());
            }
            merchantReportService.updateReport(merchantReportDto);
            operatedLogService.save(merchantReportDto.getMerchantReportInfo().getId(), MerchantEnum.MERCHANT_LOG_TYPE.REPORT, "修改报备信息", "修改报备信息");
        }
        return CommonResult.success(merchantReportDto);
    }

    // void sendMerchantReportMessage(Long id) {
    //     Map<String, Object> map = new HashMap<>();
    //     map.put("id", id);
    //     String jsonString = JsonUtils.toJsonString(map);
    //     log.info("sendMerchantReportMessage:{}", jsonString);
    //     extRocketMQTemplate.send(MqConstant.MERCHANT_REPORT_STATUS_TOPIC, jsonString);
    // }
}
